<?php
namespace App\Admin\Controllers;

use App\Admin\Actions\Import\ImportPDFAction;
use App\Admin\Actions\Import\StaffImport\ImportPDFAction as StaffImportImportPDFAction;
use App\Models\AdminUser;
use App\Models\Department;
use App\Models\DepartmentFile;
use App\Models\DepartmentFushu;
use App\Models\DepartmentStaff;
use App\Policies\Admin\UploadPolicy;
use App\Services\DepartmentService;
use App\Traits\ApiResponse;
use Dcat\Admin\Admin;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Widgets\Card;
use Illuminate\Http\Request;

class DepartmentFileUploaderController extends AdminController
{
    use ApiResponse;

    public function index(Content $content)
    {
        Admin::script($this->formScript());
        Admin::css(asset('css/admin/uploader_page.css'));
        $admin_user = AdminUser::find(Admin::user()->id);

        $bz_department = null;
        $dj_department = null;
        if ($admin_user->dwdm) {
            # 可以上传
            $bz_department = Department::findByDwdm($admin_user->dwdm);
        }
        if ($admin_user->ddb_dwdm) {
            $dj_department = Department::findByDwdm($admin_user->ddb_dwdm);
        }
        $html = '';
        if ($bz_department) {
            $bz_policy = UploadPolicy::make($bz_department, $admin_user);
            $can_upload = $bz_policy->can_upload();

            $html_bz = '';
            
            $department_file = DepartmentFile::query()->where('dwdm', $bz_department->dwdm)->first();
            $pdf_origin_name = $bz_department->getBzFileShouleName() . '.pdf';
            $ppt_origin_name = $bz_department->getBzFileShouleName() . '.pptx';

            $bz_html = '';
            if ($bz_department->file_type == Department::FILE_TYPE_BZ_SHUZHI) {
                $bz_model_ppt = new ImportPDFAction($bz_department, DepartmentFile::OFFICE_FILE_TYPE_PPT);
                $ppt_file = $department_file;
                $bz_html .= view('admin.pages.department_file_uploader.upload', ['title' => '述职PPT', 'can_upload' => $can_upload, 'modal' => $bz_model_ppt, 'office_file_type' => DepartmentFile::OFFICE_FILE_TYPE_PPT, 'file' => $department_file, 'origin_name' => $ppt_origin_name]);
                
                $bz_model_pdf = new ImportPDFAction($bz_department);
                $bz_html .= view('admin.pages.department_file_uploader.upload', ['title' => '述职PPT转PDF版本', 'can_upload' => $can_upload, 'modal' => $bz_model_pdf, 'office_file_type' => DepartmentFile::OFFICE_FILE_TYPE_PDF, 'file' => $department_file, 'origin_name' => $pdf_origin_name]);
            } else if ($bz_department->file_type == Department::FILE_TYPE_BZ_KHB) {
                $bz_model_pdf = new ImportPDFAction($bz_department);
                $bz_html .= view('admin.pages.department_file_uploader.upload', ['title' => '班子考核表', 'can_upload' => $can_upload, 'modal' => $bz_model_pdf, 'office_file_type' => DepartmentFile::OFFICE_FILE_TYPE_PDF, 'file' => $department_file, 'origin_name' => $pdf_origin_name]);
            }
            if ($bz_html) {
                $card1 = Card::make('', $bz_html)->class('card-uploader', true);
                $html_bz .=  $card1->render();
            }

            $fushu_departments = DepartmentFushu::getFushuByDwdm($bz_department->dwdm);
            if ($fushu_departments) {
                $modal = new StaffImportImportPDFAction($bz_department, 'fushu');
                $view_html = view('admin.pages.department_file_uploader.fushu_upload', ['can_upload' => $can_upload,'modal' => $modal, 'fushu_departments' => $fushu_departments]);
                $html_bz .= Card::make('附属单位考核表<span class="filename-tips">文件名称格式：xxx（单位名称）班子考核表.pdf</span>', $view_html)->class('card-uploader', true)->render();
            }

            $personals = DepartmentStaff::query()->where('dwdm', $bz_department->dwdm)->orderBy('order', 'asc')->get();
            $modal = new StaffImportImportPDFAction($bz_department);
            $view_html = view('admin.pages.department_file_uploader.staff_upload', ['can_upload' => $can_upload, 'modal' => $modal, 'personals' => $personals]);
            $html_bz .= Card::make('领导人员考核表<span class="filename-tips">文件名称格式：xxx（人名）考核表.pdf</span>', $view_html)->class('card-uploader', true)->render();


            # 提交审核按钮
            $tool = $bz_department->getStatusTextForCardHeader();;
            if ($bz_policy->can_submit_verify()) {
                $tool = '<a href="javascript:void(0)" data-url="'.admin_route('department.file.submit_audit', ['dwdm' => $bz_department->dwdm]).'" class="btn btn-danger submit-audit">提交审核</a>';
                if ($bz_department->status == Department::STATUS_VERIFY_FAILED && $bz_department->fail_reason) {
                    $tool .= "<br/><span>".$bz_department->fail_reason."</span>";
                }
            }
            $html .= Card::make('行政述职材料', $html_bz)->class('card-outer', true)->tool($tool)->render();
        }

        # 党建
        if ($dj_department) {
            $dj_html = '';
            $dj_policy = UploadPolicy::make($dj_department, $admin_user);
            $dj_can_upload = $dj_policy->can_upload();
            
            $department_file = DepartmentFile::query()->where('dwdm', $dj_department->dwdm)->first();
            $pdf_origin_name = $dj_department->getFileShouldName() . '.pdf';
            $ppt_origin_name = $dj_department->getFileShouldName() . '.pptx';
            if ($dj_department->file_type == Department::FILE_TYPE_DJ_SHUZHI) {
                $dj_model_ppt = new ImportPDFAction($dj_department, DepartmentFile::OFFICE_FILE_TYPE_PPT);
                $dj_html .= view('admin.pages.department_file_uploader.upload', ['title' => '述职PPT', 'can_upload' => $dj_can_upload, 'modal' => $dj_model_ppt, 'office_file_type' => DepartmentFile::OFFICE_FILE_TYPE_PPT, 'file' => $department_file, 'origin_name' => $ppt_origin_name]);

                $dj_model_pdf = new ImportPDFAction($dj_department);
                $dj_html .= view('admin.pages.department_file_uploader.upload', ['title' => '述职PPT转PDF版本', 'can_upload' => $dj_can_upload, 'modal' => $dj_model_pdf, 'office_file_type' => DepartmentFile::OFFICE_FILE_TYPE_PDF, 'file' => $department_file, 'origin_name' => $pdf_origin_name]);
            } else if ($dj_department->file_type == Department::FILE_TYPE_DJ_GZZJ) {
                $dj_model_pdf = new ImportPDFAction($dj_department);
                $dj_html .= view('admin.pages.department_file_uploader.upload', ['title' => '党建工作总结', 'can_upload' => $dj_can_upload, 'modal' => $dj_model_pdf, 'office_file_type' => DepartmentFile::OFFICE_FILE_TYPE_PDF, 'file' => $department_file, 'origin_name' => $pdf_origin_name]);
            }
            if ($dj_html) {
                $fail_reason = '';
                if ($dj_department->status == Department::STATUS_VERIFY_FAILED && $dj_department->fail_reason) {
                    $fail_reason = "<span class='text-danger'>（".$dj_department->fail_reason."）</span>";
                }
                # 提交审核按钮
                $tool = $dj_department->getStatusTextForCardHeader();
                if ($dj_policy->can_submit_verify()) {
                    $tool = '<a href="javascript:void(0)" data-url="'.admin_route('department.file.submit_audit', ['dwdm' => $dj_department->dwdm]).'" class="btn btn-danger submit-audit">提交审核</a>';
                }
                $card2 = Card::make('党建述职材料' . $fail_reason, $dj_html)->tool($tool)->class('card-uploader', true);
                $html .= $card2->render();
            }
        }
        return $content->body("<div>".$html."</div>");
    }

    public function downloadFile($id, Request $request)
    {
        $admin_user = AdminUser::find(Admin::user()->id);
        $department_file = DepartmentFile::find($id);
        if (!$department_file) {
            exit('文件不存在');
        }
        $department = Department::findByDwdm($department_file->dwdm);
        if (!$department) {
            exit('文件不存在');
        }
        if (!UploadPolicy::make($department, $admin_user)->can_download()) {
            exit('文件不存在');
        }
        $office_file_type = $request->get('office_file_type', 'pdf');
        $filepath = $department_file->getFilePathByOfficeFileType($office_file_type);
        if (!$filepath || ($filepath && !file_exists(file_local_path($filepath)))) {
            exit('文件不存在');
        }

        return response()->download(file_local_path($filepath));
    }


    public function readFile($id, Request $request)
    {
        $admin_user = AdminUser::find(Admin::user()->id);
        $show_type = $request->get('show_type', 'dw');
        if ($show_type == 'staff') {
            $department_staff = DepartmentStaff::find($id);
            if (!$department_staff) {
                exit('文件不存在');
            }
            $department = Department::findByDwdm($department_staff->dwdm);
            $filepath = $department_staff->filepath;
        } else if ($show_type == 'fushu') {
            $department_fushu = DepartmentFushu::find($id);
            if (!$department_fushu) {
                exit('文件不存在');
            }
            $department = Department::findByDwdm($department_fushu->dwdm);
            $filepath = $department_fushu->filepath;
        } else {
            $department_file = DepartmentFile::find($id);
            if (!$department_file) {
                exit('文件不存在');
            }
            $department = Department::findByDwdm($department_file->dwdm);
            $office_file_type = $request->get('office_file_type', 'pdf');
            $filepath = $department_file->getFilePathByOfficeFileType($office_file_type);
        }
        if (!$department || !$filepath || ($filepath && !file_exists(file_local_path($filepath)))) {
            exit('文件不存在');
        }
        if (!UploadPolicy::make($department, $admin_user)->can_view()) {
            exit('不允许查看');
        }

        $path = file_host_path($filepath).'?v='.time(); // 网络路径
        return '<iframe src="'.config('app.url').'/js/pdfjs/web/viewer.html?file='.$path.'" frameborder="0" style=" width: 100%; height: 100%"></iframe>';
    }

    public function submitAudit(Request $request)
    {
        $admin_user = AdminUser::find(Admin::user()->id);
        $dwdm = $request->get('dwdm');
        if (!$dwdm) {
            return $this->failed('单位不存在');
        }
        $department = Department::findByDwdm($dwdm);
        if (!$department) {
            return $this->failed('单位不存在');
        }
        if (!UploadPolicy::make($department, $admin_user)->can_submit_verify()) {
            return $this->failed('不允许上传');
        }
        $department_file = DepartmentFile::query()->where('dwdm', $department->dwdm)->first();
        if (!$department_file) {
            return $this->failed('请上传完所有的材料再提交审核');
        }

        // $errors = $department->checkAllFilesReady();
        // if ($errors) {
        //     return $this->failed(implode("<br/>", $errors));
        // }
        $department->update(['status' => Department::STATUS_VERIFY_PENDING, 'fail_reason' => null]);
        return $this->message('success');
    }


    private function formScript()
    {
        return Admin::script(
            <<<JS
                $(".submit-audit").click(function() {
                    var sumit_url = $(this).data('url')
                    Dcat.swal.fire({
                        text: '请确定所有行政述职材料都已上传完成',
                        showCancelButton: true,
                        confirmButtonText: '确定提交审核',
                        cancelButtonColor: '#d33',
                        cancelButtonText: `取消`,
                        allowOutsideClick: false,
                    }).then((result) => {
                        if (result.value) {
                            $.ajax({
                                type: 'post',
                                url: sumit_url,
                                success: function(res) {
                                    if (res.status == 'success') {
                                        Dcat.swal.fire({
                                            text: '提交成功，请等待审核通知',
                                            allowOutsideClick: false,
                                            showCancelButton: false,
                                            focusConfirm: false,
                                            confirmButtonText: '关闭',
                                            confirmButtonColor: '#0171fb',
                                            onClose: () => {
                                                location.reload()
                                            }
                                        })
                                    } else {
                                        Dcat.swal.fire({
                                            html: "<div style='text-align: left'>"+res.message+"</div>",
                                            allowOutsideClick: false,
                                            showCancelButton: false,
                                            focusConfirm: false,
                                            confirmButtonText: '关闭',
                                            confirmButtonColor: '#0171fb',
                                        })
                                    }
                                }
                            })
                        } else {
                            Dcat.swal.close()
                        }
                    });
                })
            JS
            );
    }

    public function downloadDwAllFiles(Request $request)
    {
        $admin_user = AdminUser::find(Admin::user()->id);
        $download_type = $request->get('download_type');
        if ($download_type == 'all_ppt') {
            if (!$admin_user->isSuperManger()) {
                exit('无法下载');
            }
            $type = $request->get('type', Department::TYPE_BZ);
            $zippath = (new DepartmentService)->downloadPPtx($type);
            if ($zippath && file_exists(file_local_private_path($zippath))) {
                return response()->download(file_local_private_path($zippath));
            }
        }if ($download_type == 'all_files') {
            if (!$admin_user->isSuperManger()) {
                exit('无法下载');
            }
            $type = $request->get('type', Department::TYPE_BZ);
            $zippath = (new DepartmentService)->downloadAllFiles($type);
            if ($zippath && file_exists(file_local_private_path($zippath))) {
                return response()->download(file_local_private_path($zippath));
            }
        } else {
            $dwdm = $request->get('dwdm', '');
            if (!$dwdm) {
                exit('无法下载');
            }
            $department = Department::findByDwdm($dwdm);
            if (!$admin_user->isSuperManger() && ($dwdm != $admin_user->dwdm || $dwdm != $admin_user->ddb_dwdm)) {
                exit('无法下载');
            }
            
    
            $zippath = (new DepartmentService)->downloadDwAllFiles($department);
            if ($zippath && file_exists(file_local_private_path($zippath))) {
                return response()->download(file_local_private_path($zippath));
            }
        }
        exit('无法下载');
    }
}